package com.lsk.mobile;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.api.RedPackApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.lsk.util.*;

import java.rmi.Remote;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/7/17 0017.
 */
public class MobileServices {
    Cache cache= Redis.use();
    public Record getWxConfigByOrgId(String orgId,int type){
        String sql="SELECT *from weixin_public_account_info where orgId='"+orgId+"' and type="+type;
        Record record= Db.findFirstByCache("weixinConfig",MD5.md5(sql),sql);
        return record;
    }

    /**
     * 根据机构号查询商品列表
     * @param orgId
     * @return
     */
    public List<Record> getCommodityList(String orgId,String unionId){
        String element=getElementName(orgId,unionId);
        String sql="SELECT id,name,imgPath,originalMoney,"+element+" as money   from shop_commodity where orgId='"+orgId+"'";
        List<Record> recordList=Db.find(sql);
        for (int i=0;i<recordList.size();i++){
            Record record=recordList.get(i);
            String id=record.getStr("id");
            List<Record> list=getCommodityImgs(id);
            record.remove("imgPath");
            record.set("imgPath",list);
            recordList.set(i,record);
        }
        return recordList;
    }

    /**
     * 根据商品Id获取图片列表
     * @param commodityId
     * @return
     */
    public List<Record> getCommodityImgs(String commodityId){
        String sql="SELECT *from shop_commodity_imgpath where commodityId='"+commodityId+"'";
        List<Record> list=Db.find(sql);
        return list;
    }
    /**
     * 根据机构号，会员unionId等级得到商品价格对应字段
     */
    public String getElementName(String orgId,String unionId){
        String sql="SELECT  * from yx_member  where unionId='"+unionId+"' and orgId='"+orgId+"'";
        Record record=Db.findFirst(sql);
        String result="money";
        if (record!=null){
            int grade=record.getInt("grade");
            if (grade==1){
                result="oneMoney";
            }else if (grade==2){
                result="twoMoney";
            }else if (grade==3){
                result="threeMoney";
            }else if (grade==4){
                result="fourMoney";
            }else if (grade==5){
                result="fiveMoney";
            }else {
                result="money";
            }
        }
        return result;
    }

    /**
     * 保存会员
     * @param openId
     * @param unionId
     * @param orgId
     * @param name
     * @param heardUrl
     */
    public void saveMember(String openId,String unionId,String orgId,String name,String heardUrl,String parentId){
        SaveMemberThread saveMemberThread=new SaveMemberThread();
        saveMemberThread.setOpenId(openId);
        saveMemberThread.setOrgId(orgId);
        saveMemberThread.setUnionId(unionId);
        saveMemberThread.setName(name);
        saveMemberThread.setHeardUrl(heardUrl);
        saveMemberThread.setParentId(parentId);
        saveMemberThread.run();
    }
    public ReturnData getMemberAddressService(String unionId,String orgId){
        ReturnData returnData=new ReturnData();
        try {
            Record member=getMemberByunionId(unionId,orgId);
            String id=member.getStr("id");
            String sql="SELECT *from yx_member_address where memberId='"+id+"'";
            Record record=Db.findFirst(sql);
            returnData.setCode("00000");
            returnData.setData(record);
            returnData.setMsg("请求成功");
        }catch (Exception e){
            Syslog.error(e);
            returnData.setCode("00000");
            returnData.setMsg(e+"");
        }
        return returnData;
    }


    /**
     * 下单支付
     * @param openId
     * @param orgId
     * @param unionId
     * @param commodityId
     * @param number
     * @return
     */

    public ReturnData payService(String openId, String orgId, String unionId, String commodityId, int number){
        Record memberRecord=getMemberByunionId(unionId,orgId);
        int money=commodityMoneyByUnionId(unionId,commodityId,orgId);
        money=money*number;//总价格
        String orderId= UtilOrder.createOrder(Long.parseLong(orgId));
        Record commodity=getCommodityById(commodityId);
        String commodityName=commodity.getStr("name");
        Record orderRecord=new Record().set("id",orderId).set("money",money).set("memberId",memberRecord.getStr("id"))
                .set("orgId",orderId).set("createTime",new Date()).set("commodityId",commodityId).set("number",number);
        cache.setex(orderId,60*30,orderRecord);//将订单信息放入缓存
        Record wxConfig=getWxConfigByOrgId(orgId,0);
        Map<String, String> params=new HashMap<>();
        params.put("appid",wxConfig.getStr("appId"));
        params.put("mch_id",wxConfig.getStr("mch_id"));
        params.put("nonce_str",System.currentTimeMillis() + "");
        params.put("body",commodityName);
        params.put("out_trade_no",orderId);
        params.put("total_fee",money+"");
        params.put("notify_url",wxConfig.getStr("domain")+"/mobile/callBack");
        params.put("trade_type","JSAPI");
        params.put("openid",openId);
        String paternerKey="05134b1ba4254e9d98ccb44e04560807";
        String sign=PaymentKit.createSign(params,paternerKey);
        params.put("sign",sign);
        Syslog.info(params);
        String  xmlStr = PaymentApi.pushOrder(params);
        Map<String,String> map= PaymentKit.xmlToMap(xmlStr);
        Syslog.info(map);

        /*h5签名*/
        Map h5Map = new HashMap();
        h5Map.put("appId", wxConfig.getStr("appId"));
        h5Map.put("timeStamp", (System.currentTimeMillis() / 1000) + "");
        h5Map.put("nonceStr", UtilUUID.getUUID());
        h5Map.put("package", "prepay_id=" + map.get("prepay_id"));
        h5Map.put("signType", "MD5");
        sign = PaymentKit.createSign(h5Map, paternerKey);
        String tempPackage = h5Map.get("package").toString();
        h5Map.remove("package");
        h5Map.put("package1", tempPackage);
        h5Map.put("paySign", sign);
        ReturnData returnData=new ReturnData();
        returnData.setData(h5Map);
        return returnData;
    }
    /**
     * 根据会员unionId，商品Id 查询出该商品对此会员的售价
     */
    public int commodityMoneyByUnionId(String unionId,String commodityId,String orgId){
        String memberSql="SELECT *from yx_member where unionId='"+unionId+"' and orgId='"+orgId+"'";
        Record memberRecord=Db.findFirst(memberSql);
        int memberGrade=memberRecord.getInt("grade");
        String sql="SELECT *from shop_commodity where id='"+commodityId+"'";
        Record commodityRecord=Db.findFirst(sql);//查询出商品信息
        int money=0;
        if (memberGrade==0){//原价
            money=commodityRecord.getInt("money");
        }else if (memberGrade==1){
            money=commodityRecord.getInt("oneMoney");
        }else if (memberGrade==2){
            money=commodityRecord.getInt("twoMoney");
        }else if (memberGrade==3){
            money=commodityRecord.getInt("threeMoney");
        }else if (memberGrade==4){
            money=commodityRecord.getInt("fourMoney");
        }else if (memberGrade==5){
            money=commodityRecord.getInt("fiveMoney");
        }else {
            Syslog.error("会员等级异常");
        }
        return money;
    }
    /**
     * 根据unionId查询会员信息
     */
    public Record getMemberByunionId(String unionId,String orgId){
        String sql="SELECT *from yx_member where unionId='"+unionId+"' and orgId='"+orgId+"'";
        Record member=Db.findFirstByCache("oneDay", MD5.md5(sql),sql);
        return member;
    }
    /**
     * 根据商品ID查询商品信息
     */
    public Record getCommodityById(String commodityId){
        String sql="SELECT *from shop_commodity where id='"+commodityId+"'";
        Record commodity=Db.findFirst(sql);
        return commodity;
    }
    /**
     * 回调函数
     */
    public void callBackService(Map<String, String> map){
        String out_trade_no=map.get("out_trade_no");//订单号
        String transaction_id=map.get("transaction_id");
        Record orderRecord=cache.get(out_trade_no);
        orderRecord.set("state","1");
        orderRecord.set("wxId",transaction_id);
        boolean saveOrder=Db.save("yx_order","id",orderRecord);
        if (saveOrder==false){
            Syslog.error("微信回调，保存订单信息至数据库失败"+JsonUtil.getJsonStr(orderRecord));
        }
        String addressId=orderRecord.getStr("addressId");
        Record address=cache.get(addressId);
        boolean saveAddress=Db.save("yx_member_address","id",address);
        if (saveAddress==false){
            Syslog.error("微信回调，保存地址信息至数据库失败"+JsonUtil.getJsonStr(saveAddress));
        }
        String memberId=orderRecord.getStr("memberId");//会员Id
        String orgId=orderRecord.getStr("orgId");
        int money=orderRecord.getInt("money");
        String commodityId=orderRecord.getStr("commodityId");
        String orderId=orderRecord.getStr("id");
        Map threadMap=new HashMap();
        threadMap.put("commodityId",commodityId);
        threadMap.put("memberId",memberId);
        threadMap.put("orgId",orgId);
        threadMap.put("orderId",orderId);
        /*执行返利*/
        RebateThread rebateThread=new RebateThread(threadMap);
        Thread thread=new Thread(rebateThread);
        thread.start();
    }
    /**
     * 查询会员地址
     */
    public Record getMemberAddress(String memberId){
        String sql="SELECT *from yx_member_address where memberId='"+memberId+"'";
        Record record=Db.findFirst(sql);
        return record;
    }

    /**
     * 会员返利
     */
    public void memberRebate(String memberId,String orgId,double money){
        String orgSql="SELECT *from yx_rule where orgId='"+orgId+"' ORDER BY grade ";
        String sql="SELECT *from yx_member_tree where memberId='"+memberId+"' ";
        Record record=Db.findFirst(sql);
        List<Record> list=Db.find(orgSql);
        for (int i=0;i<list.size();i++){
            Record tempRecord=list.get(i);
            double grade=tempRecord.getDouble("grade");
            if (i==0){//一级返利
                String oneMemberId=record.getStr("oneParentId");
                String memberSql="SELECT *from yx_member where id='"+oneMemberId+"'";
                Record memberRecord=Db.findFirstByCache("oneDay", MD5.md5(memberSql),memberSql);
                money=money*grade;//返利的金额
                int intMoney= (int) (money*100);
                redPackService(intMoney,memberRecord.getStr("orgId"),memberRecord.getStr("openId"));
            }else if (i==1){
                String oneMemberId=record.getStr("twoParentId");
                String memberSql="SELECT *from yx_member where id='"+oneMemberId+"'";
                Record memberRecord=Db.findFirstByCache("oneDay", MD5.md5(memberSql),memberSql);
                money=money*grade;//返利的金额
                int intMoney= (int) (money*100);
                redPackService(intMoney,memberRecord.getStr("orgId"),memberRecord.getStr("openId"));
            }else if (i==2){
                String oneMemberId=record.getStr("threeParentId");
                String memberSql="SELECT *from yx_member where id='"+oneMemberId+"'";
                Record memberRecord=Db.findFirstByCache("oneDay", MD5.md5(memberSql),memberSql);
                money=money*grade;//返利的金额
                int intMoney= (int) (money*100);
                redPackService(intMoney,memberRecord.getStr("orgId"),memberRecord.getStr("openId"));
            }else if (i==3){
                String oneMemberId=record.getStr("fourParentId");
                String memberSql="SELECT *from yx_member where id='"+oneMemberId+"'";
                Record memberRecord=Db.findFirstByCache("oneDay", MD5.md5(memberSql),memberSql);
                money=money*grade;//返利的金额
                int intMoney= (int) (money*100);
                redPackService(intMoney,memberRecord.getStr("orgId"),memberRecord.getStr("openId"));
            }else if (i==4){
                String oneMemberId=record.getStr("fiveParentId");
                String memberSql="SELECT *from yx_member where id='"+oneMemberId+"'";
                Record memberRecord=Db.findFirstByCache("oneDay", MD5.md5(memberSql),memberSql);
                money=money*grade;//返利的金额
                int intMoney= (int) (money*100);
                redPackService(intMoney,memberRecord.getStr("orgId"),memberRecord.getStr("openId"));
            }else {
                Syslog.info("数据异常");
            }
        }

    }
    /**
     * 查询会员等级
     */



    /**
     * 返利红包
     * @return
     */
    public   void   redPackService(int money,String orgId,String openId){

        Record wxConfig=getWxConfigByOrgId(orgId,0);
        Map<String, String> map=new HashMap<>();
        map.put("nonce_str",(System.currentTimeMillis() / 1000) + "");
        String id=UuidUtil.get32UUID().substring(8);
        map.put("mch_billno",id);
        map.put("mch_id",wxConfig.getStr("mch_id"));
        map.put("wxappid",wxConfig.getStr("appId"));
        map.put("send_name","小乖购");
        map.put("re_openid",openId);
        map.put("total_amount",money+"");
        map.put("wishing","推广多多，返利多多");
        map.put("client_ip","127.0.0.1");
        map.put("act_name","你是最棒的~，么么哒");
        map.put("total_num","1");
        map.put("remark","返利红包");
        String paternerKey="05134b1ba4254e9d98ccb44e04560807";
        String sign=PaymentKit.createSign(map,paternerKey);
        map.put("sign",sign);
        String result=RedPackApi.sendRedPack(map,"D:\\dingyuankeji\\admin\\src\\main\\resources\\payFile\\apiclient_cert.p12",wxConfig.getStr("mch_id"));
        Syslog.info(result);
    }
    public static void main(String[] strings){
        Map<String, String> map=new HashMap<>();
        map.put("nonce_str",(System.currentTimeMillis() / 1000) + "");
        String id=UuidUtil.get32UUID().substring(8);
        map.put("mch_billno",id);
        map.put("mch_id","1491318292");
        map.put("wxappid","wxeae06ad6f1ac729b");
        map.put("send_name","馨冉国际");
        map.put("re_openid","o3zbnwh25CGt6RSoCtjQ3g26mR7U");
        map.put("total_amount","15000");
        map.put("wishing","馨冉国际");
        map.put("client_ip","127.0.0.1");
        map.put("act_name","馨冉国际");
        map.put("total_num","1");
        map.put("remark","返利红包");
        String paternerKey="05134b1ba4254e9d98ccb44e04560807";
        String sign=PaymentKit.createSign(map,paternerKey);
        map.put("sign",sign);
        String result=RedPackApi.sendRedPack(map,"D:\\dingyuankeji\\admin\\src\\main\\resources\\payFile\\apiclient_cert.p12","1491318292");
        Syslog.info(result);

    }
}
